package com.hwpt.chesedemo

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.Surface
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.navigation.compose.rememberNavController
import com.hwpt.chesedemo.presentation.navigation.NavGraph
import com.hwpt.chesedemo.presentation.theme.ChessPlatformTheme
import com.hwpt.chesedemo.presentation.theme.LanguageManager
import com.hwpt.chesedemo.presentation.theme.LocalStrings
import com.hwpt.chesedemo.data.local.PreferenceManager
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.flow.first

@AndroidEntryPoint
class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            ChessPlatformTheme {
                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = androidx.compose.material3.MaterialTheme.colorScheme.background
                ) {
                    val navController = rememberNavController()
                    val context = LocalContext.current

                    // 在应用启动时加载保存的语言设置
                    LaunchedEffect(Unit) {
                        val savedLanguage = PreferenceManager.getLanguage(context).first()
                        LanguageManager.currentLanguageCode = savedLanguage
                    }

                    // 使用 CompositionLocalProvider 提供正确的字符串资源
                    CompositionLocalProvider(
                        LocalStrings provides LanguageManager.currentStrings()
                    ) {
                        NavGraph(navController = navController)
                    }
                }
            }
        }
    }
}